package uk.ac.bbk.dcs.pakdd2014;

import java.io.*;
import java.util.HashMap;
import java.util.HashSet;

public class Parser {
	
	public static HashSet<SalesDate> parseST() throws IOException{
		
		HashMap<Integer,SalesDate> hm= new HashMap<Integer,SalesDate>();
		File f= new File("data_filtered/SaleTrain.csv");
		BufferedReader br = new BufferedReader(new FileReader(f));
		String s;
		while((s=br.readLine())!=null){
			String[] arr=s.split(",");
			
			int mod=Integer.parseInt(arr[0]);
			int com= Integer.parseInt(arr[1]);
			int quantity = Integer.parseInt(arr[3]);
			
			String[] date=arr[2].split("/");
			int month=Integer.parseInt(date[1]);
			int year=Integer.parseInt(date[2]);
			
			int key=mod*100+com;
			if(hm.containsKey(key)){
				hm.get(key).addSale(year, month, quantity);
			} else{
				SalesDate sd=new SalesDate(mod,com);
				sd.addSale(year, month, quantity);
				hm.put(key, sd);
			}
		}
		br.close();
		return new HashSet<SalesDate>(hm.values());
	}
	
public static HashSet<RepairDate> parseRT() throws IOException{
		
		HashMap<Integer,RepairDate> hm= new HashMap<Integer,RepairDate>();
		File f= new File("data_filtered/RepairTrain.csv");
		BufferedReader br = new BufferedReader(new FileReader(f));
		String s;
		while((s=br.readLine())!=null){
			String[] arr=s.split(",");
			
			int mod=Integer.parseInt(arr[0]);
			int com= Integer.parseInt(arr[1]);
			int quantity = Integer.parseInt(arr[4]);
			
			String[] date1=arr[2].split("/");
			int month1=Integer.parseInt(date1[1]);
			int year1=Integer.parseInt(date1[2]);
			
			String[] date2=arr[3].split("/");
			int month2=Integer.parseInt(date2[1]);
			int year2=Integer.parseInt(date2[2]);
			
			int key=mod*100+com;
			if(hm.containsKey(key)){
				hm.get(key).addRepair(year1, month1, year2, month2, quantity);
			} else{
				RepairDate sd=new RepairDate(mod,com);
				sd.addRepair(year1, month1, year2, month2, quantity);
				hm.put(key, sd);
			}
		}
		br.close();
		return new HashSet<RepairDate>(hm.values());
	}
	
	public static void main(String[] args) throws IOException{
		HashSet<SalesDate> sales=parseST();
		HashSet<RepairDate> repairs=parseRT();
		HashSet<MCLifeProbability> mclps = MCLifeProbability.buildAllMC(repairs, sales, true);
		CSVGenerator.generate(mclps);
        FileOutputStream fileOut = new FileOutputStream("datasets/MCLifeProbability.serialized");
        ObjectOutputStream out = new ObjectOutputStream(fileOut);
        out.writeObject(mclps);
        out.close();
        fileOut.close();
		System.out.println("constructed");
	}
}
